/*
 * Project Name spring-boot-tools
 * File Name ToolsAppServer
 * Package Name com.huxiaosu.tools.common
 * Create Time 2024/4/18
 * Create by name：liujie
 */
package com.huxiaosu.tools.common;

import com.huxiaosu.tools.common.service.LauncherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.*;

import java.util.*;

/**
 * Description
 *
 * @author liujie
 * @date 2024/4/18 22:31
 */
@Slf4j
public class ToolsAppServer {

    public static ConfigurableApplicationContext run(Class<?> source, String... args) {
        SpringApplicationBuilder builder = createSpringAppServer(source, args);
        ConfigurableApplicationContext run = builder.run(args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String localPort = environment.getProperty("server.port", "8080");
        log.info("{} is started; use port = [{}] ", source.getSimpleName(), localPort);
        return run;

    }

    public static SpringApplicationBuilder createSpringAppServer(Class<?> source, String... args) {
        final String appName = source.getSimpleName();
        SpringApplicationBuilder builder = new SpringApplicationBuilder(source);
        ConfigurableEnvironment environment = new StandardEnvironment();

        // 加载自定义组件
        List<LauncherService> launcherList = new ArrayList<>();
        ServiceLoader.load(LauncherService.class).forEach(launcherList::add);
        launcherList.stream()
            .sorted(Comparator.comparing(LauncherService::getOrder))
            .toList()
            .forEach(launcherService -> launcherService.launcher(builder, appName));
        return builder;
    }

}
